import React, { Component } from 'react'
import { Table, Spin, Form, Row, Col, Input, Button, Tree } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import { getNewTreeData, findRowData } from 'lib/fun'

const TreeNode = Tree.TreeNode;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      loading: false
    }
  }

  componentDidMount() {
    this.onLoadData();
  }

  onSelect = (info, e) => {
    if(e.selected){
      var selected = findRowData(this.state.treeData, info, 'orgId');
      if(selected){
        this.props.handleSelect(selected);
      }
    }else{
      this.props.handleSelect({});
    }
    // e.node.onExpand();
    // this.onLoadData(e.node);
  }

  onLoadData = (treeNode) => {
    var self = this;
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'orgId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        self.setState({
          loading: false
        });
        resolve();
      }else{
        // var {  } = this.search;
        Ajax({
          url: '/organization/list',
          data: {
            orgParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'orgId');
            }else{
              treeData = data.list
            }
            self.setState({
              loading: false,
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }
  
  render() {
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <TreeNode title={item.orgName} key={item.orgId} value={item.orgCode}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode title={item.orgName} key={item.orgId} value={item.orgCode} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);

    return (
    	<div>
        <Tree 
          ref="tree"
          autoExpandParent
          onSelect={this.onSelect} 
          loadData={this.onLoadData}
        >
          {treeNodes}
        </Tree>
    	</div>
    )
  }
}

module.exports = ModuleName
